package controllers

import (
	"fmt"
	bc "translate_backend/controllers/BaseController"
	"translate_backend/db"
	"translate_backend/models"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"gopkg.in/mgo.v2/bson"
)

// 处理登录注册
type SignCon struct {
	bc.BaseController
}

// =======用户登录==========
func (con *SignCon) AdminLogin(c *gin.Context) {

	// var paraData = c.ParserPostData()
	// username := paraData["username"]
	// pwdPlaint := paraData["password"].(string)

	var muser models.User
	if perr := c.ShouldBindJSON(&muser); perr != nil {
		con.ServeError(403, "", nil, c)
		return
	}
	username := muser.Username
	pwdPlaint := muser.Password

	//fmt.Println("账户:", username, pwdPlaint)

	if username == "" || pwdPlaint == "" {
		con.ServeError(403, "", nil, c)
	} else {
		//检验用户名和密码
		var user models.User
		db.FindOneByCondition(bson.M{"username": username}, "user", map[string]int{"_id": 0}, &user)

		//用户不存在
		if user.ID == "" {
			con.ServeError(404, "用户不存在", nil, c)
			return
		}

		//检验密码
		res := user.CheckUserPassword(pwdPlaint)
		if res {
			con.ServeSuccess(bc.M{"session": user.Password, "username": user.Username, "nickname": user.Nickname}, "", c)
		} else {
			con.ServeError(403, "密码错误", nil, c)
			return

		}

	}

}

// 获取全部(分页)/搜索
func (con *SignCon) GetUserList(c *gin.Context) {

	limitFields := map[string]int{"_id": 0, "gender": 0, "password": 0}

	con.GetAllByPage("user", nil, limitFields, []string{"-isSupperAdmin"}, c)

}

// 创建普通用户
func (con *SignCon) Create(c *gin.Context) {

	var mUser = struct {
		Username      string `bson:"username"   json:"username"  form:"username"`
		Nickname      string `bson:"nickname"   json:"nickname"`
		Password      string `bson:"password"   json:"password"  form:"password"`                // MD5(id+原文)
		AdminPassword string `bson:"adminPassword"   json:"adminPassword"  form:"adminPassword"` // MD5(id+原文)                               //修改人
	}{}
	c.ShouldBindJSON(&mUser)

	// println("mUser.AdminPassword", mUser.AdminPassword)
	// println("isValidAdmin", isValidAdmin(mUser.AdminPassword))

	if mUser.Username == "" || mUser.Password == "" || isValidAdmin(mUser.AdminPassword) == false {
		con.ServeError(403, "用户名或密码不能为空", nil, c)
		return
	}

	res, user := insertNormalAdmin(mUser.Username, mUser.Nickname, mUser.Password)
	if res {
		con.ServeSuccess(user, "", c)
	} else {
		con.ServeError(500, "", nil, c)
	}

}

// 更新
func (con *SignCon) Update(c *gin.Context) {

	var mUser = struct { // MD5(id+原文)
		AdminPassword string `bson:"adminPassword"   json:"adminPassword"  form:"adminPassword"` // MD5(id+原文)                               //修改人
	}{}
	c.ShouldBindBodyWith(&mUser, binding.JSON)
	if isValidAdmin(mUser.AdminPassword) == false {
		con.ServeError(401, "超级管理员密码错误", nil, c)
		return
	}
	con.UpdateObjectByID("user", c)
}

// 删除
func (con *SignCon) Delete(c *gin.Context) {

	var mUser = struct { // MD5(id+原文)
		AdminPassword string `bson:"adminPassword"   json:"adminPassword"  form:"adminPassword"` // MD5(id+原文)                               //修改人
	}{}

	//ShouldBindBodyWith 可以执行多次
	c.ShouldBindBodyWith(&mUser, binding.JSON)

	if isValidAdmin(mUser.AdminPassword) == false {
		con.ServeError(401, "超级管理员密码错误", nil, c)
		return
	}

	//fmt.Println("mUser.AdminPassword:", mUser.AdminPassword)

	con.DeleteObjectByID("user", c)
}

// 插入超级管理员信息
func insertNormalAdmin(username, nickname, pwd string) (bool, models.User) {

	user := models.User{
		ID:        "",
		Nickname:  nickname,
		Username:  username,
		Authority: "",
		Avatar:    ""}

	user.SetupInitValues()
	user.IsSupperAdmin = 0  //超级管理员标记,理论上只允许有一位
	user.SetupPassword(pwd) // 预设密码
	//fmt.Println("密码:", user.Password)

	res := db.InsertOne(user, "user")
	if res {
		fmt.Println("创建成功:", username)
	} else {
		fmt.Println("创建失败:", username)
	}

	return res, user

}

// 验证是否超级管理员密码
func isValidAdmin(pwd string) bool {
	var users []models.User
	q := map[string]interface{}{"isSupperAdmin": 1}
	db.FindAll("user", q, map[string]int{"_id": 0}, nil, &users, 0, false)
	//fm

	if len(users) > 0 {
		var user = users[0]
		return user.CheckUserPassword(pwd)
	}

	return false
}
